#include "cJSON.h"
#include "log.h"
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // 从JSON字符串提取值
    // 创建一个JSON字符串
    char *json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
    // 解析json字符串
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("json解析失败");
        return -1;
    }
    cJSON * namejson = cJSON_GetObjectItem(root, "name");
    cJSON * agejson = cJSON_GetObjectItem(root, "age");
    cJSON * cityjson = cJSON_GetObjectItem(root, "city");
    if (namejson == NULL || agejson == NULL || cityjson == NULL)
    {
        log_error("json解析失败");
        return -1;
    }

    char *name = namejson->valuestring;
    int age = agejson->valueint;
    char *city = cityjson->valuestring;
    log_info("name:%s,age:%d,city:%s", name, age, city);

    // 通过值组合一个json字符串
    cJSON *root2 = cJSON_CreateObject();
    cJSON_AddStringToObject(root2, "name", "zhangsan");
    cJSON_AddNumberToObject(root2, "age", 18);
    cJSON_AddStringToObject(root2, "city", "beijing");
    // 无格式打印
    char *json_str = cJSON_PrintUnformatted(root2);
    log_info("json_str:%s", json_str);

    // 释放内存
    cJSON_Delete(root);
    cJSON_Delete(root2);
    free(json_str);
    
    return 0;
}